/**
 */
package com.dingpeikeji.quickdeer.core.modules.bus.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.dingpeikeji.quickdeer.core.common.config.Global;
import com.dingpeikeji.quickdeer.core.common.persistence.Page;
import com.dingpeikeji.quickdeer.core.common.utils.DateUtils;
import com.dingpeikeji.quickdeer.core.common.utils.StringUtils;
import com.dingpeikeji.quickdeer.core.common.web.BaseController;
import com.dingpeikeji.quickdeer.core.modules.bus.entity.TCompBus;
import com.dingpeikeji.quickdeer.core.modules.bus.service.TCompBusService;
import com.dingpeikeji.quickdeer.core.modules.driver.entity.TDrivers;
import com.dingpeikeji.quickdeer.core.modules.driver.service.TDriversService;
import com.dingpeikeji.quickdeer.core.modules.exchg.entity.TBusExchg;
import com.dingpeikeji.quickdeer.core.modules.exchg.service.TBusExchgService;
import com.dingpeikeji.quickdeer.core.modules.exchg.web.TBusExchgController;
import com.dingpeikeji.quickdeer.core.modules.realsche.entity.TRealscheVehi;
import com.dingpeikeji.quickdeer.core.modules.realsche.service.TRealscheService;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.Office;
import com.dingpeikeji.quickdeer.core.modules.sys.service.OfficeService;
import com.dingpeikeji.quickdeer.core.modules.sys.utils.UserUtils;
import com.dingpeikeji.quickdeer.core.modules.vehi.entity.TRealscheVehis;
import com.dingpeikeji.quickdeer.core.modules.vehi.service.TRealscheVehisService;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TCargotype;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.TCargotypeService;

/**
 * 巴士管理Controller
 * 
 * @author Zhaoy
 * @version 2016-05-20
 */
@Controller
@RequestMapping(value = "${adminPath}/bus/tCompBus")
public class TCompBusController extends BaseController {

	@Autowired
	private TCompBusService tCompBusService;

	@Autowired
	private TCargotypeService tCargotypeService;
	@Autowired
	private TDriversService tDriversService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private TRealscheService tRealschesService;

	@ModelAttribute
	public TCompBus get(@RequestParam(required = false) String id) {
		if (StringUtils.isNotBlank(id)) {
			return tCompBusService.get(id);
		} else {
			return new TCompBus();
		}
	}

	@RequiresPermissions("bus:tCompBus:view")
	@RequestMapping(value = { "list", "" })
	public String list(TCompBus tCompBus, HttpServletRequest request, HttpServletResponse response, Model model) {
		String types = request.getParameter("types");
		if (types != null && !types.equals("")) {
			tCompBus.setOffice(UserUtils.getUser().getOffice());
		}

		String busstatus = request.getParameter("busstatus");
		if (busstatus == null || "".equals(busstatus))
			tCompBus.setBusstatus("0");
		
		Page<TCompBus> page = tCompBusService.findPage(new Page<TCompBus>(request, response), tCompBus);
		
		model.addAttribute("page", page);
		model.addAttribute("types", types);

		return "modules/bus/tCompBusList";
	}
	
	@RequestMapping(value = "state")
	public String state(TCompBus tCompBus,TRealscheVehi tRealscheVehi, HttpServletRequest request, HttpServletResponse response, Model model) {
		String types = request.getParameter("types");
		//tCompBus.setOffice( UserUtils.getUser().getOffice());
		//TCompBus bus  = tCompBusService.getBusByLicenseno(tCompBus.getLicenseno());
		if(tCompBus.getLicenseno()!=null){
			tRealscheVehi.setLicno(tCompBus.getLicenseno());
		}
		if(tRealscheVehi.getCreateDateQueryEnd()==null&&tRealscheVehi.getCreateDateQueryStart()==null){
			tRealscheVehi.setCreateDateQueryEnd(new Date());
			tRealscheVehi.setCreateDateQueryStart(new Date());
		}
		Page<TRealscheVehi> page = tRealschesService.findVehiPage(new Page<TRealscheVehi>(request, response), tRealscheVehi) ;
		for(int i=0;i<page.getList().size();i++){
			try{
				page.getList().get(i).setBusname(tCargotypeService.get(page.getList().get(i).getCargotypeid().toString()).getTypename());
			}catch (Exception e) {
				page.getList().remove(i);
				i--;
				page.setCount(page.getCount()-1);
			}
		}
		model.addAttribute("page", page);
		model.addAttribute("tCompBus", tCompBus);
		model.addAttribute("tRealscheVehi", tRealscheVehi);
		model.addAttribute("types", types);
		return "modules/bus/tCompBusState";
	}

	@RequiresPermissions("bus:tCompBus:edit")
	@RequestMapping(value = "form")
	public String form(TCompBus tCompBus, Model model, HttpServletRequest request) {
		
		if (tCompBus.getOffice() == null || tCompBus.getOffice().getId() == null) {
			tCompBus.setOffice(UserUtils.getUser().getOffice());
		}
		// 查出所有客运公司
		List<Map<String, Object>> mapList = Lists.newArrayList();
		Office qryOffice = new Office();
		qryOffice.setFlatType(Office.FLAT_TYPE_BUS);
		List<Office> list = officeService.findListByTerm(qryOffice);
		for (int i = 0; i < list.size(); i++) {
			Office e = list.get(i);
			Map<String, Object> map = Maps.newHashMap();
			map.put("id", e.getId());
			map.put("pId", e.getParentId());
			map.put("pIds", e.getParentIds());
			map.put("name", e.getName());
			mapList.add(map);
		}
		model.addAttribute("officelist", mapList);
		
		String types = request.getParameter("types");
		model.addAttribute("types", types);
		model.addAttribute("tCompBus", tCompBus);
		
		//车型改为平台维护，不跟客运公司挂钩		
		TCargotype tCargo = new TCargotype();
		ArrayList<TCargotype> cartypelist = (ArrayList<TCargotype>) tCargotypeService.findList(tCargo);
		model.addAttribute("tCargotypeList", cartypelist);

		//获取公司的所有驾驶员，如果未选择则是空
		TDrivers tDrivers = new TDrivers();
		tDrivers.setOffice(tCompBus.getOffice());
		ArrayList<TDrivers> lists = (ArrayList<TDrivers>) tDriversService.findList(tDrivers);
		model.addAttribute("tDrvlist", lists);
		
		// 界面显示联系人id为归属公司名
//		model.addAttribute("owner", tCompBus.getOffice().getName());
		model.addAttribute("owner", UserUtils.getUser().getOffice().getName());

		return "modules/bus/tCompBusForm";
	}
	
	@RequiresPermissions("bus:tCompBus:view")
	@RequestMapping(value = "formview")
	public String formview(TCompBus tCompBus, Model model, HttpServletRequest request) {
		
		if (tCompBus.getOffice() == null || tCompBus.getOffice().getId() == null) {
			tCompBus.setOffice(UserUtils.getUser().getOffice());
		}
		// 查出所有客运公司
		List<Map<String, Object>> mapList = Lists.newArrayList();
		Office qryOffice = new Office();
		qryOffice.setFlatType(Office.FLAT_TYPE_BUS);
		List<Office> list = officeService.findListByTerm(qryOffice);
		for (int i = 0; i < list.size(); i++) {
			Office e = list.get(i);
			Map<String, Object> map = Maps.newHashMap();
			map.put("id", e.getId());
			map.put("pId", e.getParentId());
			map.put("pIds", e.getParentIds());
			map.put("name", e.getName());
			mapList.add(map);
		}
		model.addAttribute("officelist", mapList);
		
		String types = request.getParameter("types");
		model.addAttribute("types", types);
		model.addAttribute("tCompBus", tCompBus);
		
		//车型改为平台维护，不跟客运公司挂钩		
		TCargotype tCargo = new TCargotype();
		ArrayList<TCargotype> cartypelist = (ArrayList<TCargotype>) tCargotypeService.findList(tCargo);
		model.addAttribute("tCargotypeList", cartypelist);

		//获取公司的所有驾驶员，如果未选择则是空
		TDrivers tDrivers = new TDrivers();
		tDrivers.setOffice(tCompBus.getOffice());
		ArrayList<TDrivers> lists = (ArrayList<TDrivers>) tDriversService.findList(tDrivers);
		model.addAttribute("tDrvlist", lists);
		
		// 界面显示联系人id为归属公司名
//		model.addAttribute("owner", tCompBus.getOffice().getName());
		model.addAttribute("owner", UserUtils.getUser().getOffice().getName());

		return "modules/bus/tCompBusView";
	}
	
	@RequiresPermissions("bus:tCompBus:view")
	@RequestMapping(value = "offSellForm")
	public String offSellForm(TCompBus tCompBus, String updateorview, Model model, HttpServletRequest request) {
		Date tomorrow = new Date();
		tomorrow.setDate(tomorrow.getDate() + 1);
		model.addAttribute("tomorrow", DateUtils.formatDate(tomorrow, "yyyy-MM-dd"));
		model.addAttribute("tomorrow", tomorrow);
		
		if (tCompBus.getOffbegin() == null)
			tCompBus.setOffbegin(tomorrow);
		
		if (tCompBus.getOffend() == null)
			tCompBus.setOffend(tomorrow);
		
		if (updateorview == null)
			updateorview = "";
		
		model.addAttribute("tCompBus", tCompBus);
		model.addAttribute("updateorview", updateorview);
		String types = request.getParameter("types");
		model.addAttribute("types", types);
	
		return "modules/bus/offSellBusForm";
	}

	@RequestMapping(value = "ajaxList")
	@ResponseBody
	public List<TDrivers> ajaxList(HttpServletRequest request, HttpServletResponse response, Model model) {
		// 通过officeid 查询司机信息
		String officeids = request.getParameter("officeids");
		TDrivers tDrivers = new TDrivers();
		Office office = new Office();
		office.setId(officeids);
		tDrivers.setOffice(office);
		ArrayList<TDrivers> arrayList = (ArrayList<TDrivers>) tDriversService.findList(tDrivers);
		ArrayList<TDrivers> list = new ArrayList<TDrivers>();
		for (int i = 0; i < arrayList.size(); i++) {
			if (arrayList.get(i).getAssignflag().equals("0")) {
				list.add(arrayList.get(i));
			}
		}
		return list;

	}

	@RequestMapping(value = "cargoTypeList")
	@ResponseBody
	public List<TCargotype> cargoTypeList(HttpServletRequest request, HttpServletResponse response, Model model) {

		// 通过officeid 查询车型信息
		String officeids = request.getParameter("officeids");
		TCargotype tDrivers = new TCargotype();
		Office office = new Office();
		office.setId(officeids);
		tDrivers.setOffice(office);
		ArrayList<TCargotype> arrayList = (ArrayList<TCargotype>) tCargotypeService.findList(tDrivers);

		return arrayList;

	}

	@RequiresPermissions("bus:tCompBus:edit")
	@RequestMapping(value = "save")
	public String save(TCompBus tCompBus, TBusExchg busExchg, TBusExchg busExchg1, Model model,
			RedirectAttributes redirectAttributes, HttpServletRequest request) {
		if (!beanValidator(model, tCompBus)) {
			return form(tCompBus, model, request);
		}
		String types = request.getParameter("types");
		model.addAttribute("types", types);
		/*
		 * if(types.equals("1")){
		 * tCompBus.setOffice(UserUtils.getUser().getOffice()); }
		 */
		// 设置联系人id为归属公司id
		tCompBus.setOwnerid(tCompBus.getOffice().getId());
		// 设置操作人为当前登录用户
		tCompBus.setCreateby(UserUtils.getUser().getId());
		tCompBusService.save(tCompBus);

		addMessage(redirectAttributes, "保存巴士管理成功");
		return "redirect:" + Global.getAdminPath() + "/bus/tCompBus/?repage&types=" + types + "";
	}

	/*@RequiresPermissions("bus:tCompBus:edit")
	@RequestMapping(value = "delete")
	public String delete(TCompBus tCompBus, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		tCompBus.setDelflag("1");
		tCompBusService.delete(tCompBus);
		String types = request.getParameter("types");
		addMessage(redirectAttributes, "停用巴士管理成功");
		return "redirect:" + Global.getAdminPath() + "/bus/tCompBus/?repage&types=" + types + "";
	}*/

	@RequiresPermissions("bus:tCompBus:edit")
	@RequestMapping(value = "enableBus")
	public String enableBus(TCompBus tCompBus, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		tCompBus.setBusstatus(TCompBus.ST_IN_USE);
		tCompBusService.update(tCompBus);
		String types = request.getParameter("types");
		addMessage(redirectAttributes, "启用巴士管理成功");
		return "redirect:" + Global.getAdminPath() + "/bus/tCompBus/?repage&types=" + types + "";
	}
	
	@RequiresPermissions("bus:tCompBus:edit")
	@RequestMapping(value = "offSellBus")
	public String offSellBus(TCompBus tCompBus, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		tCompBus.setBusstatus(TCompBus.ST_OFF_SELL);
		tCompBusService.update(tCompBus);
		String types = request.getParameter("types");
		addMessage(redirectAttributes, "巴士下架成功");
		return "redirect:" + Global.getAdminPath() + "/bus/tCompBus/?repage&types=" + types + "";
	}


	@RequiresPermissions("bus:tCompBus:edit")
	@RequestMapping(value = "disableBus")
	public String disableBus(TCompBus tCompBus, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		tCompBus.setBusstatus("1");
		tCompBusService.update(tCompBus);
		String types = request.getParameter("types");
		addMessage(redirectAttributes, "停用巴士管理成功");
		return "redirect:" + Global.getAdminPath() + "/bus/tCompBus/?repage&types=" + types + "";
	}

	/**
	 * 验证车牌号是否唯一
	 * 
	 * @param oldLicenseno
	 * @param licenseno
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("bus:tCompBus:edit")
	@RequestMapping(value = "checkLicenseno")
	public String checkLicenseno(String oldLicenseno, String licenseno) {
		if (licenseno != null && licenseno.equals(oldLicenseno)) {
			return "true";
		} else if (licenseno != null && tCompBusService.getBusByLicenseno(licenseno) == null) {
			return "true";
		}
		return "false";
	}

}
